<template>
  <s-layout>
    <view class="container">
      <view class="form-container">
        <!-- 头部标题 -->
        <view class="header-box" v-if="!formData.id">
          <text
            class="cicon-edit"
            style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
          ></text>
          <text class="title">新增消防安全培训</text>
        </view>

        <view class="header-box" v-if="formData.id">
          <text
            class="cicon-edit"
            style="color: #0052d9; font-size: 44rpx; margin-right: 20rpx"
          ></text>
          <text class="title">修改消防安全培训</text>
        </view>

        <!-- 基本信息区块 -->
        <view class="form-card">
          <fui-section
            title="基本信息"
            line-width="3px"
            line-color="#0052d9"
            isLine
            size="34"
            style="padding: 0; margin-bottom: 30rpx"
          >
          </fui-section>

          <!-- 培训标题 -->
          <fui-input
            label="安全培训"
            placeholder="请输入培训名称"
            v-model="formData.title"
            required
          >
            <text
              class="cicon-title"
              slot="prefix"
              style="color: #0052d9; font-size: 40rpx"
            ></text>
          </fui-input>

          <!-- 培训培训日期 -->
          <view class="form-item" @click="showDatePicker = true">
            <text
              class="cicon-time"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>

            <text style="color: #4f4e4e">培训日期:</text>
            <fui-input
              placeholder="请选择培训日期"
              v-model="formData.date"
              :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
              :borderBottom="false"
			  disabled
            >
            </fui-input>
            <fui-date-picker
              :show="showDatePicker"
              type="3"
              @change="confirmDate"
              @cancel="showDatePicker = false"
            >
            </fui-date-picker>
          </view>

          <!-- 培训地点 SAIL输入框-->
          <view class="form-item">
            <text
              class="cicon-location-on"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <text style="color: #4f4e4e">培训地点:</text>
            <fui-input
              placeholder="请输入演练地点"
              v-model="formData.address"
              :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
              :borderBottom="false"
            >
            </fui-input>
          </view>

          <!-- 参与人数 -->
          <view class="form-item">
            <text
              class="cicon-person"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <text style="color: #4f4e4e">参与人数：</text>
            <fui-input-number
              :model-value="formData.participants"
              custom
              backgroundColor="#FFF"
              :size="30"
              :width="60"
              margin="0"
            >
              <fui-icon name="minussign" :size="48" color="#0052d9"></fui-icon>
              <template v-slot:plus>
                <fui-icon
                  name="plussign-fill"
                  :size="48"
                  color="#0052d9"
                ></fui-icon>
              </template>
            </fui-input-number>
          </view>
        </view>

        
        <!-- 演练详情区块 -->
        <view class="form-card">
          <fui-section
            title="培训详情"
            line-width="3px"
            line-color="#0052d9"
            isLine
            size="34"
            style="padding: 0; margin-bottom: 30rpx"
          >
          </fui-section>

          <!-- 培训开始时间 -->
          <view class="form-item" @click="showTimePicker2 = true">
            <text
              class="cicon-time"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>

            <text style="color: #4f4e4e">开始时间:</text>
            <fui-input
              placeholder="请选择培训开始时间"
              v-model="formData.startTime"
              :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
              :borderBottom="false"
			  disabled
            >
            </fui-input>
            <fui-date-picker
              :show="showTimePicker2"
              type="6"
              @change="confirmTime2"
              @cancel="showTimePicker2 = false"
            >
            </fui-date-picker>
          </view>
          <!-- 培训结束时间 -->
          <view class="form-item" @click="showTimePicker = true">
            <text
              class="cicon-time"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <text style="color: #4f4e4e">结束时间:</text>
            <fui-input
              placeholder="请选择培训结束时间"
              v-model="formData.endTime"
              :padding="['0rpx', '20rpx', '0rpx', '20rpx']"
              :borderBottom="false"
			  disabled
            >
            </fui-input>
            <fui-date-picker
              :show="showTimePicker"
              type="6"
              @change="confirmTime"
              @cancel="showTimePicker = false"
            >
            </fui-date-picker>
          </view>

          <!-- 培训内容 -->
          <text class="form-item-title">培训内容：</text>
          <view class="form-item">
            <text
              class="cicon-target"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <fui-textarea
              v-model="formData.content"
              isCounter
              height="80rpx"
              placeholder="请输入培训主要内容"
            ></fui-textarea>
          </view>

          <!-- 培训总结 -->
          <text class="form-item-title">培训总结：</text>
          <view class="form-item">
            <text
              class="cicon-target"
              style="color: #0052d9; font-size: 40rpx; margin-right: 20rpx"
            ></text>
            <fui-textarea
              v-model="formData.summary"
              isCounter
              height="80rpx"
              placeholder="请输入培训总结"
            ></fui-textarea>
          </view>
        </view>
      </view>

      <!-- 多媒体区块 -->
      <view class="form-card">
        <fui-section
          title="安全培训多媒体"
          line-width="3px"
          line-color="#0052d9"
          isLine
          size="34"
          style="padding: 0; margin-bottom: 30rpx"
        >
        </fui-section>

        <!-- 附件上传组件 -->
        <s-upload
          v-model="formData.files"
          :required="true"
          :initial-images="formData.image"
          :initial-videos="formData.video"
          :initial-files="formData.file"
          :max-image-count="maxImageCount"
          :max-file-count="maxFileCount"
          :max-video-count="maxVideoCount"
          :max-total-files="maxTotalFiles"
          :upload-url="uploadUrl"
        ></s-upload>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-btn" @click="handleSubmit">
        <text class="btn-text">提交安全培训</text>
      </view>
    </view>
  </s-layout>
</template>

<script setup lang="ts">
import { ref } from "vue";
import sheep from "@/sheep";
import { onLoad } from "@dcloudio/uni-app";
import sUpload from "@/sheep/components/s-upload/s-upload.vue";
const formData = ref({
});

onLoad((options) => {
  if (options.id) {
    const params = {
      tr_id: options.id,
      company_id: sheep.$store("user").userInfo.company_id,
    };
    formData.value.id = options.id;
    sheep.$api.qy_security.detail(params).then((res) => {
      console.log("params", params);
      console.log("detail", res);
      
      // 获取详情数据
      const detailData = res.data;
      
      // 转换现有的图片和视频数据为s-upload格式
      const files = [];
      
      // 处理图片数据
      if (detailData.images && detailData.images.length > 0) {
        detailData.images.forEach((img, index) => {
          files.push({
            filePath: img.replace(/^https?:\/\/[^\/]+/, ""),
            fileType: "image",
            fileUrl: img,
            id: `file_image_${index}`,
            originalName: `image_${index}`,
            progress: 100,
            uploading: false
          });
        });
      }
      
      // 处理视频数据
      if (detailData.videos && detailData.videos.length > 0) {
        detailData.videos.forEach((video, index) => {
          files.push({
            filePath: video.replace(/^https?:\/\/[^\/]+/, ""),
            fileType: "video",
            fileUrl: video,
            id: `file_video_${index}`,
            originalName: `video_${index}`,
            progress: 100,
            uploading: false
          });
        });
      }
      
      // 更新表单数据
      formData.value = {
        ...detailData,
        files: files
      };
    });
  } else {
    formData.value = {
      title: "",
      status: "",
      type: "",
      date: "",
      startTime: "",
      endTime: "",
      content:
        "",
      summary:
        "",
      address: "",
      views: null,
      participants: "",
      files: []
    };
  }
});
// 选择器相关
const showDatePicker = ref(false);
const showTimePicker = ref(false);
const showTimePicker2 = ref(false);



const confirmDate = (e: any) => {
  formData.value.date = e.result;
  showDatePicker.value = false;
  console.log("data", e);
};
const confirmTime2 = (e: any) => {
  formData.value.startTime = e.result;
  showTimePicker2.value = false;
};
const confirmTime = (e: any) => {
  formData.value.endTime = e.result;
  showTimePicker.value = false;
};

// ================ 常量配置 ================
// 上传URL地址
const uploadUrl = "/app_api.php?t=upload&op=image_upload&role=company&type=study";

// 上传文件数量限制
const maxImageCount = ref(3); // 最大图片数量
const maxFileCount = ref(3); // 最大文件数量
const maxVideoCount = ref(3); // 最大视频数量
const maxTotalFiles = ref(9); // 最大附件总数量

// 表单提交
const handleSubmit = () => {
  if (!validateForm()) return;

  // 从files中分离出不同类型的文件
  const images = [];
  const videos = [];
  const files = [];

  // 处理上传的文件
  formData.value.files.forEach(file => {
    if (file.fileType === "image") {
      images.push(file.filePath);
    } else if (file.fileType === "video") {
      videos.push(file.filePath);
    } else if (file.fileType === "file") {
      files.push(file.filePath);
    }
  });

  const params = {
    tr_title: formData.value.title,
    tr_startTime: formData.value.startTime,
    tr_date: formData.value.date,
    company_id: sheep.$store("user").userInfo.company_id,
    tr_endTime: formData.value.endTime,
    tr_type: formData.value.type,
    tr_dept: formData.value.dept,
    tr_summary: formData.value.summary,
    tr_address: formData.value.address,
    tr_participants: formData.value.participants,
    tr_videos: videos,
    tr_content: formData.value.content,
    tr_views: formData.value.views,
    tr_images: images,
    tr_files: files
  };
  
  console.log("提交参数:", params);
  uni.showLoading({ title: "提交中...", mask: true });
  
  // 判断是新增还是编辑
  const apiMethod = formData.value.id ? 'update' : 'add';
  
  // 如果是编辑模式，添加ID
  if (formData.value.id) {
    params.tr_id = formData.value.id;
  }
  
  sheep.$api.qy_security[apiMethod](params).then((res) => {
    console.log("提交结果:", res);
    uni.hideLoading();
    
    if (res.code === 200) {
      uni.showToast({ title: "提交成功", icon: "success" });
      
      // 发送数据更新事件，通知其他页面刷新数据
      uni.$emit('securityDataUpdated', {
        timestamp: Date.now(),
        action: formData.value.id ? 'update' : 'add',
        moduleType: 'security'
      });
      
      setTimeout(() => uni.navigateBack(), 1500);
    } else {
      uni.showToast({ 
        title: res.msg || "提交失败，请重试", 
        icon: "none" 
      });
    }
  }).catch(err => {
    uni.hideLoading();
    console.error("提交错误:", err);
    uni.showToast({ 
      title: "提交失败，请检查网络连接", 
      icon: "none" 
    });
  });
};

const validateForm = () => {
  if (!formData.value.title) {
    uni.showToast({ title: "请填写培训标题", icon: "none" });
    return false;
  }
  if (!formData.value.date) {
    uni.showToast({ title: "请选择培训日期", icon: "none" });
    return false;
  }
  if (!formData.value.address) {
    uni.showToast({ title: "请填写培训地点", icon: "none" });
    return false;
  }
  if (!formData.value.participants || formData.value.participants <= 0) {
    uni.showToast({ title: "请填写正确的参与人数", icon: "none" });
    return false;
  }
  if (!formData.value.startTime) {
    uni.showToast({ title: "请选择开始时间", icon: "none" });
    return false;
  }
  if (!formData.value.endTime) {
    uni.showToast({ title: "请选择结束时间", icon: "none" });
    return false;
  }
  if (!formData.value.content) {
    uni.showToast({ title: "请填写培训内容", icon: "none" });
    return false;
  }
  if (!formData.value.summary) {
    uni.showToast({ title: "请填写培训总结", icon: "none" });
    return false;
  }
  if (!formData.value.files || formData.value.files.length === 0) {
    uni.showToast({ title: "请至少上传一个附件", icon: "none" });
    return false;
  }
  return true;
};
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  background: #f8f9fa;
  min-height: 100vh;
}

.header-box {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  .title {
    font-size: 40rpx;
    font-weight: 700;
    color: #1a1a1a;
  }
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 82, 217, 0.1);
}

.form-item-title {
  display: flex;
  align-items: center;
  padding-top: 20rpx;
  padding-left: 32rpx;
  font-size: 32rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  font-size: 32rpx;
  border-bottom: 1rpx solid #eee;
}

/* 移除旧的上传样式 */

.submit-btn {
  background: linear-gradient(135deg, #0052d9, #2979ff);
  border-radius: 50rpx;
  height: 90rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 40rpx 0;
  .btn-text {
    color: #fff;
    font-size: 34rpx;
    font-weight: 500;
  }
}
</style>
